package groovy.jmx.builder.modelmbean

import groovy.jmx.builder.node.AttrNodeData
import groovy.jmx.builder.node.MBeanNodeData
import groovy.jmx.builder.node.OpNodeData
import groovy.jmx.builder.node.ParamNodeData
import java.lang.reflect.Constructor
import javax.management.MBeanParameterInfo





class CollectorHelper {
    public static List<MBeanParameterInfo> collectParamInfo(OpNodeData data) {
        List<MBeanParameterInfo> result = []
        data?.parameters.each {param ->
            result.add(new MBeanParameterInfo(param.name, param.type, param.description))
        }
        return result
    }

    public static List<MBeanParameterInfo> collectParamInfo(def op) {
        List<MBeanParameterInfo> result = []
        op.parameterTypes.each {paramType ->
            result.add(new MBeanParameterInfo(paramType.name, paramType.name, "Parameter"))
        }
        return result
    }

    public static AttrNodeData getAttrNodeData(MBeanNodeData data, MetaProperty property) {
        def attr;
        if (data && property) {
            for (AttrNodeData node in data.attributes) {
                if (node?.name.toLowerCase().equals(property.name.toLowerCase())) {
                    attr = node
                    break
                }
            }
        }
        return attr
    }

    public static OpNodeData getOpNodeData(MBeanNodeData data, def op) {
        def result
        if (data && op) {
            def ops
            if (op instanceof Constructor) {
                ops = data.constructors
            } else if (op instanceof MetaMethod) {
                ops = data.operations
            }

            for (OpNodeData node in ops) {
                boolean match = true
                int opParamSize = op.parameterTypes.size()
                int nodeParamSize = node?.parameters.size()
                if (op.name.equals(node.name) && opParamSize == nodeParamSize) {
                    int i = 0
                    for (ParamNodeData param in node.parameters) {
                        if (param.type.equals(op.parameterTypes[i++].name)) {
                            match &= true
                        } else {
                            match &= false
                        }
                    }
                } else {
                    match = false
                }

                if (match == true) {
                    result = node
                    break
                }
            }
        }
        return result
    }

    public static String capitalize(String value) {
        if (!value) return null
        if (value.length() == 1) return value.toUpperCase()
        return (value.length() > 1) ? value[0].toUpperCase() + value[1..-1] : value.toUpperCase()
    }

}